﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace QT.Text
{
    /// <summary>
    /// 字符串操作类
    /// </summary>
    public class String
    {
        /// <summary>
        /// 截取制定长度的字串
        /// </summary>
        /// <param name="inString"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string substring(string inString, int len)
        {
            string outString = "";
            string tmpString="";
            int outLen=0;
            for (int i = 0; i < inString.Length; i++)
            {
                tmpString = inString.Substring(i, 1);
                if (Length(tmpString) == 2) outLen += 2;
                else outLen += 1;
                outString += tmpString;

                if (outLen >= len) break;
            }
            
            return outString;
        }

        /// <summary>
        /// 计算字符串长度，中文占两位
        /// </summary>
        /// <param name="inString">字符串</param>
        /// <returns>int</returns>
        public static int Length(string inString)
        {
            int len = 0;

            for (int i = 0; i < inString.Length; i++)
            {
                if (Regex.IsMatch(inString.Substring(i, 1), @"[^x00-xff]")) len += 2;
                else len += 1;
            }

            return len;
        }
    }
}
